package com.xzmzhp.controller.power;

import com.xzmzhp.constant.ReturnConstant;
import com.xzmzhp.pojo.power.Competence;
import com.xzmzhp.service.power.RequestPathService;
import com.xzmzhp.utils.return_tool.ReturnData;
import com.xzmzhp.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author 王源(xm)
 * @Date: 2020/12/9 13:49
 * @Description: 请求路径信息
 */
@Controller
@RequestMapping("/power")
public class RequestPathController {

    @Autowired
    private RequestPathService requestPathService;

    @Autowired
    WebApplicationContext applicationContext;

    /**
     * 查询权限路径表所有数据
     *
     * @return ReturnData对象 成功返回 data 失败返回错误信息和错误状态码
     */
    @GetMapping("/findAll")
    @ResponseBody
    public ReturnData findAll() {
        return ReturnData.ok(requestPathService.findAll());
    }


    /**
     * 根据请求路径模糊查询
     *
     * @param url 请求路径
     * @return ReturnData
     */
    @GetMapping("/findByUrl")
    @ResponseBody
    public ReturnData findByUrl(String url) {
        return requestPathService.findByUrl(url);
    }

    /**
     * 根据请求路径查询所对应的权限
     *
     * @param url 请求路径
     * @return 路径信息
     */
    @GetMapping("/findByOneUrl")
    @ResponseBody
    public ReturnData findByOneUrl(String url) {
        List<Competence> list = requestPathService.findByOneUrl(url);
        if (StringUtils.isNotNull(list)) {
            return ReturnData.ok(list);
        }
        return ReturnData.error(ReturnConstant.FAIL, "没有找到对应路径的权限信息");
    }


    /**
     * 批量添加请求路径
     *
     * @return 是否成功
     */
    @GetMapping("/addRequestPaths")
    @ResponseBody
    public ReturnData addRequestPaths() {

        RequestMappingHandlerMapping mapping = applicationContext.getBean(RequestMappingHandlerMapping.class);
        //获取url与类和方法的对应信息
        Map<RequestMappingInfo, HandlerMethod> map = mapping.getHandlerMethods();
        List<String> urls = new ArrayList<>();

        for (RequestMappingInfo info : map.keySet()) {
            //获取url的Set集合，一个方法可能对应多个url
            Set<String> patterns = info.getPatternsCondition().getPatterns();
            urls.addAll(patterns);
        }

        Integer i = requestPathService.addRequestPaths(urls);
        return ReturnData.ok(i);
    }
}
